package edu.whu.puppygo.service.Impl;

import edu.whu.puppygo.config.OssConfig;
import edu.whu.puppygo.dao.GrowthRecordDao;
import edu.whu.puppygo.dao.PetDao;
import edu.whu.puppygo.dto.GrowthRecordDto;
import edu.whu.puppygo.entity.GrowthRecord;
import edu.whu.puppygo.exception.BackendException;
import edu.whu.puppygo.service.GrowthRecordService;
import edu.whu.puppygo.util.OssUtil;
import edu.whu.puppygo.util.VoConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author guanruwang
 * @date 2023/12/2$
 */
@Service
@Slf4j
public class GrowthRecordServiceImpl implements GrowthRecordService {
    @Resource
    private OssUtil ossUtil;

    @Resource
    private PetDao petDao;

    @Resource
    private GrowthRecordDao growthRecordDao;

    @Override
    public GrowthRecord addGrowthRecord(GrowthRecordDto growthRecordDto) {
        long petId = growthRecordDto.getPetId();
        List<MultipartFile> images = growthRecordDto.getImages();
        String record = growthRecordDto.getRecord();
        petDao.findById(petId).orElseThrow(() -> new RuntimeException("未找到宠物"));
        if (images == null || images.isEmpty()) {
            throw new BackendException("图片不能为空");
        }
        List<String> urls = new ArrayList<>();
        for (MultipartFile image : images) {
            String fileName = image.getOriginalFilename();
            String url = ossUtil.uploadFile(image, OssConfig.getFullUrl() + OssConfig.getGrowthRecordPic() + fileName);
            log.info("上传图片成功，url为：{}", url);
            urls.add(url);
        }
        GrowthRecord growthRecord = VoConvertUtil.convertEntity(growthRecordDto, GrowthRecord.class);
        growthRecord.setImgList(urls.toString());

        return growthRecordDao.save(growthRecord);
    }
}
